/**
 * meiguang8.com
 * Copyright (C) 2016-2019 All Rights Reserved.
 */
package com.yuanchuang.yp.mall.framework.extend.dubbo.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;
import com.yuanchuang.yp.mall.framework.extend.ArgumentsLengthManayException;
import com.yuanchuang.yp.mall.framework.extend.ValidateResult;
import com.yuanchuang.yp.mall.framework.extend.utils.ValidateUtil;

import java.util.Objects;

/**
 * class_name: GlobalParameterFilter
 * package: com.yuanchuang.yp.mall.framework.extend.dubbo.filter
 * describe: TODO
 * @author: yuanyuan.zhu
 * creat_date: 2019/7/10
 * creat_time: 19:14
 **/
@Activate(group = Constants.PROVIDER)
public class GlobalParameterFilter implements Filter {
    /**
     * do invoke filter.
     * <p>
     * <code>
     * // before filter
     * Result result = invoker.invoke(invocation);
     * // after filter
     * return result;
     * </code>
     *
     * @param invoker    service
     * @param invocation invocation.
     * @return invoke result.
     * @throws RpcException
     * @see Invoker#invoke(Invocation)
     */
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 要求只能有一个参数，不能有多个参数
        Object[] arguments = invocation.getArguments();
        if (!Objects.isNull(arguments) && arguments.length>1) {
            return new RpcResult(ArgumentsLengthManayException.argumentsLengthManayException);
        }
        else if (!Objects.isNull(arguments) ) {
            ValidateResult validate = ValidateUtil.validate(arguments[0]);
            if (!validate.isResult()) {
                return new RpcResult(ArgumentsLengthManayException.argumentsLengthManayException);
            }
        }
        return invoker.invoke(invocation);
    }
}
